// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Odbc;
using System.Linq;
using JetBrains.Annotations;

namespace SnapObjects.Data.Odbc
{
    internal abstract class OdbcAdoDbCommandBase : AdoDbCommand
    {
        public OdbcAdoDbCommandBase(
            [NotNull] string sqlText,
            IEnumerable<IAdoDbParameter> parameters,
            bool addExceptionToTransaction,
            CommandType commandType = CommandType.Text)
            : base(sqlText, parameters, addExceptionToTransaction, commandType)
        {
        }

        protected override void CreateArrayParameter(
            IDbCommand command,
            ITypeMapper typeMapper,
            IAdoDbParameter parameter,
            IEnumerable value)
        {
            command.CommandText = this.CreateArrayParameter(
                command.CommandText, typeMapper, @"\" + parameter.ParameterName, value);
        }

        protected override void PreCreateCommand(DataContext dataContext)
        {
            // Do something driver-related, 
            // eg: replace SqlText, add Parameters for ODBC.
            if (this.Parameters.Count() == 0)
            {
                return;
            }
            
            // replace array parameters in SqlText
            this.ReplaceArrayParameters(dataContext);

            var tokenizer = new SqlSyntaxTokenizer(this.SqlText);

            var helper = (OdbcSqlGenerationHelperBase)dataContext.AdoDbSqlProvider.SqlGenerationHelper;

            IList<IAdoDbParameter> adoDbParameters = new List<IAdoDbParameter>();

            for (var i = 0; i < tokenizer.Tokens.Count; i++)
            {

                var adoDbParameter = this.Parameters.FirstOrDefault(
                    p => p.ParameterName.Equals(tokenizer.Tokens[i], StringComparison.OrdinalIgnoreCase));

                if (adoDbParameter != null)
                {
                    tokenizer.Tokens[i] = helper.ParameterPlaceholder.ToString();
                    adoDbParameters.Add(adoDbParameter);
                }
            }

            this.SqlText = tokenizer.GetSqlString();

            if (adoDbParameters.Count > 0)
            {
                this.Parameters = adoDbParameters;
            }
        }

        private void ReplaceArrayParameters(DataContext dataContext)
        {
            if (this.Parameters == null)
            {
                return;
            }

            var typeMapper = dataContext.AdoDbSqlProvider.TypeMapper;

            foreach (var parameter in this.Parameters)
            {
                if (typeof(IEnumerable).IsAssignableFrom(parameter.ClrType)
                        && parameter.ClrType != typeof(string)
                        && parameter.ClrType != typeof(byte[]))
                {
                    this.SqlText = this.CreateArrayParameter(
                        this.SqlText, typeMapper,
                        @"\" + parameter.ParameterName,
                        (IEnumerable)parameter.Value);
                }
            }
        }

        protected override int GetSqlDbCode(Exception innerException)
        {
            if (innerException is OdbcException ex)
            {
                return ex.ErrorCode;
            }

            return -1;
        }
    }
}
